package com.qf.om.servlet;

import com.qf.om.entity.Admin;
import com.qf.om.myutils.DataUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//       接收登陆的信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String inputCode = req.getParameter("code");
//        验证码效验,获取session
        HttpSession session = req.getSession();
        String code = (String) session.getAttribute("code");
        long time = (long) session.getAttribute("code_time");
//        验证码有效时间效验
        if (System.currentTimeMillis() - time > 5 * 60 * 1000) {
            resp.sendRedirect("login.jsp?status=3");
            return;
        }

        if (inputCode == null || !inputCode.equals(code)) {
            resp.sendRedirect("login.jsp?status=2");
            return;
        }

        session.removeAttribute("code");
        session.removeAttribute("code_time");
//        查询因为是静态集合
        Admin admin = DataUtils.queryAdmin(username, password);
        System.out.println(DataUtils.queryAdmin(username, password));
        if (admin != null) {
            req.getSession().setAttribute("login_user", admin);
            resp.sendRedirect("index.jsp");
        } else {
            resp.sendRedirect("login.jsp?status=1");
        }
    }
}
